import java.util.Random;

public class RentThread implements Runnable {
    private final CDStore store;
    private final Logger logger;
    private final Random rand = new Random();

    public RentThread(CDStore store, Logger logger) {
        this.store = store;
        this.logger = logger;
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                int cdNumber = rand.nextInt(10) + 1;

                if (store.rent(cdNumber)) {
                    logger.log("Rented CD #" + cdNumber);
                    Thread.sleep(200 + rand.nextInt(101));
                    store.returnCD(cdNumber);
                    logger.log("Returned CD #" + cdNumber);
                } else {
                    if (rand.nextBoolean()) {
                        logger.log("Waiting for CD #" + cdNumber);
                        Thread.sleep(rand.nextInt(200));
                    } else {
                        logger.log("Abandoned rent of CD #" + cdNumber);
                    }
                }
                Thread.sleep(rand.nextInt(200));
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
